package org.hcyspartnoc.demo.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import jakarta.annotation.Resource;
import org.hcyspartnoc.demo.common.core.configuration.AliyunConfiguration;
import org.springframework.stereotype.Component;

@Component
public class AliyunSmsUtils {
    private static AliyunConfiguration aliyunConfiguration;

    @Resource
    public void setAliyunConfiguration(AliyunConfiguration aliyunConfiguration) {
        AliyunSmsUtils.aliyunConfiguration = aliyunConfiguration;
    }

    private static Config getConfig() {
        Config config = new Config()
                .setAccessKeyId(aliyunConfiguration.getAccessKeyId())
                .setAccessKeySecret(aliyunConfiguration.getAccessKeySecret());
        config.endpoint = aliyunConfiguration.getSms().getEndpoint();
        return config;
    }

    // 默认模板只支持4数字
    public static String sendNumCaptchaWithPhone(String phoneNumber) {
        // 随机验证码
        String captcha = StringUtils.randomNumStr(4);
        try {
            // 发送验证码
            Client client = new Client(getConfig());
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")//短信签名
                    .setTemplateCode("SMS_154950909")//短信模板
                    .setPhoneNumbers(phoneNumber)//这里填写接受短信的手机号码
                    .setTemplateParam("{\"code\":\"" + captcha + "\"}");
            SendSmsResponse res = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            return null;
        }
        return captcha;
    }


}
